class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if(n <= 1) return 0;

        vector<int> mem(n, prices[n-1]);
        for(int i = n-2; i >= 0; i--){
            mem[i] = max(mem[i+1], prices[i]);
        }

        int max_prof = 0;
        for(int i =0; i<n-1; i++){
            max_prof = max(mem[i+1]-prices[i], max_prof);
        }

        return max_prof;
    }
};  